import { createRouter, createWebHashHistory } from "vue-router";
import Login from "../views/login.vue";
import MainBox from "../views/MainBox.vue";
import Home from "@/views/main/home/Home.vue";
import Center from "@/views/main/center/Center.vue";
import RoutesConfig from "./config";
import store from "@/store";

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    component: Login,
  },
  {
    path: "/mainbox",
    name: "mainbox",
    component: MainBox,
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

const ConfigRouter = () => {
  RoutesConfig.forEach((item) => {
    router.addRoute("mainbox", item);
  });
  store.commit("changeConfigRouter", true);
};

// 每次跳转前判断
router.beforeEach((to, from, next) => {
  if (to.path == "/login") {
    next();
  } else {
    // 如果授权（登录过） next()
    // 未授权，重定向到 login
    if (!localStorage.getItem("token")) {
      next({ path: "/login" });
    } else {
      if (!store.state.isConfigRouter) {
        ConfigRouter();
        next({
          path: to.fullPath,
        });
      }else {
        next();
      }
    }
  }
});

ConfigRouter();

export default router;
